package thread;

import lombok.SneakyThrows;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author ZhuQi
 * @ClassName ThreadStopDemo3
 * @Date 2022/9/13 11:05
 * @Version 1.0
 * @Description 测试 加锁中断
 */
public class ThreadStopDemo3 {

    @SneakyThrows
    public static void main(String[] args) {
        ReentrantLock lock = new ReentrantLock();

        Thread thread1 = new Thread(() -> {
            lock.lock();
            try {
                while (true) {
                    System.out.println(Thread.currentThread().getName() + "------------");
                    try {
                        TimeUnit.SECONDS.sleep(1);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            } finally {
                lock.unlock();
            }
        },"thread1");
        thread1.start();

        Thread thread2 = new Thread(() -> {
            try {
                lock.lockInterruptibly();
            } catch (Exception e) {
                e.printStackTrace();
                System.out.println(Thread.currentThread().getName() + e.getMessage());
                return;
            }
            try {
                while (true) {
                    System.out.println(Thread.currentThread().getName() + "------------");
                    try {
                        TimeUnit.SECONDS.sleep(1);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            } catch (Exception e) {
                System.out.println(Thread.currentThread().getName() + e.getMessage());
            } finally {
                lock.unlock();
            }
        },"thread2");
        thread2.start();

        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        thread2.interrupt();
    }
}
